import { _decorator } from "cc";

/*
 * @Author: 李琪 liqi@lark2game.com
 * @Date: 2024-12-07 18:17:11
 * @LastEditors: 李琪 liqi@lark2game.com
 * @LastEditTime: 2024-12-10 15:28:29
 * @FilePath: /cramped-room/assets/Script/Runtime/EventManager.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
interface IEvent {
    callback: Function;
    ctx: unknown;
}
const { ccclass, property } = _decorator
@ccclass('EventManager')

export default class EventManager extends Comment {
    private static instance: EventManager;


    public static get Instance(): EventManager {
        if (!EventManager.instance) {
            EventManager.instance = new EventManager();
        }
        return EventManager.instance;
    }
    //使用字典设置事件名称
    private eventDict: Map<string, Array<IEvent>> = new Map();
    /* @author: 李琪  @change:绑定以及解绑事件
     * @date: 2024/12/07 18:20 */
    on(eventName: string, callback: Function, ctx?: unknown) {//绑定上下文ctx
        if (this.eventDict.has(eventName)) {
            this.eventDict.get(eventName)?.push({ callback, ctx });
        } else {
            this.eventDict.set(eventName, [{ callback, ctx }]);
        }
    }
    off(eventName: string, callback: Function) {
        const callbacks = this.eventDict.get(eventName);
        if (!callbacks) return;
        const index = callbacks.findIndex(callbackObj => callbackObj.callback === callback);
        index > -1 && callbacks.splice(index, 1);//取消注册的事件
    }
    emit(eventName: string, ...args: any[]) {
        const callbacks = this.eventDict.get(eventName);
        if (!callbacks) return;
        callbacks.forEach(({ callback, ctx }) => {
            ctx ? callback.apply(ctx, args) : callback(...args);//绑定上下文
        })
    }
    clear() {
        this.eventDict.clear();
    }

}
export const eventMgr = EventManager.Instance;
